package com.joey.concurrency.example.sync;

import com.joey.concurrency.annotation.NotThreadSafe;
import com.joey.concurrency.annotation.ThreadSafe;
import com.joey.concurrency.example.count.AtomicReferenceUpdaterExample;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @Author hyy
 **/
@Slf4j
@ThreadSafe
public class VolatileEnvironmentExample {

    static volatile boolean inited = false;
    static int step = 0;
    static String html = "";

    public static void init(){
        System.out.println("等待中》》》");
        //延迟操作，比如down文件
        for(int i = 1;i<10000;i++){
            html += i;
        }

        html = "<html></html>";
        inited = true;
        System.out.println("已完成");

    }

    public static void parseHtml(String html){

        while (!inited){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("解析html文档");
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        VolatileEnvironmentExample example = new VolatileEnvironmentExample();
        executorService.execute(() -> {
            example.parseHtml(html);
        });
        executorService.execute(() -> {
            example.init();
        });
        executorService.execute(() -> {
            example.init();
        });
        executorService.execute(() -> {
            example.init();
        });
        executorService.execute(() -> {
            example.init();
        });


        executorService.shutdown();
    }

}
